package com.mlizhi.kingdom;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.base.NetWorkManager;
import com.mlizhi.base.SecurityUtil;
import com.mlizhi.base.Session;
import com.mlizhi.base.Utils;
import com.mlizhi.modules.login.LoginActivity;
import com.mlizhi.modules.spec.SpecActivity;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.modules.splash.PreSettingActivity;
import com.mlizhi.utils.Constants;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends Activity {
	private Session mSession;
	private Activity mContext;
	private RequestQueue mRequestQueue;
	private boolean isCancel = false;

	int permission = 0;
	private static final int STORAGE = 0X10;
	private static final int LOCATION = 0X11;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		mSession = Session.get(getApplicationContext());
		setContentView(R.layout.activity_main);


//		if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE);
//		}else {
//			permission += 1;
//		}
//		if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE);
//		}

		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
				|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
				|| ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
			ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
					Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE}, LOCATION);
		}else {
			initView();
		}
	}

	private void initView() {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				if(!isCancel){
					long splashId = mSession.getSplashId();
					if (splashId == -1) { // 说明是第一次，还没有设置splash
						MainActivity.this.startActivity(new Intent(MainActivity.this, PreSettingActivity.class));
						MainActivity.this.finish();
					} else if (splashId == 1) {// 说明第一次以后，splash已经设置过了
						String uid = mSession.getUid();
						if (uid == null || "".equals(uid)) {
							MainActivity.this.startActivity(new Intent(MainActivity.this, SpecActivity.class));
							MainActivity.this.finish();
						} else {
							autoLogin();
//						MainActivity.this.startActivity(new Intent(MainActivity.this, AutoLoginActivity.class));
//						MainActivity.this.finish();
						}
					}
				}
			}
		}, 4500);
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
		switch (requestCode) {
//			case STORAGE: {
//				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//					permission += 1;
//					if(permission >= 2) {
//						initView();
//					}
//				} else {
//					ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE);
//					// 权限被用户拒绝了，洗洗睡吧。
//					Toast.makeText(this, "无法播放视频！", Toast.LENGTH_LONG).show();
//				}
//				break;
//			}
			case LOCATION: {
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
						&& grantResults[1] == PackageManager.PERMISSION_GRANTED
						&& grantResults[2] == PackageManager.PERMISSION_GRANTED) {
					initView();
				} else {
					ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
							Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE}, LOCATION);
					// 权限被用户拒绝了，洗洗睡吧。
//					Toast.makeText(this, "！", Toast.LENGTH_LONG).show();
				}
				break;
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		// 统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
		MobclickAgent.onPageStart("SplashScreen"); 
		MobclickAgent.onResume(this); // 统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		// （仅有Activity的应用中SDK自动调用，不需要单独写）保证onPageEnd 在onPause之前调用,因为 onPause 中会保存信息
		MobclickAgent.onPageEnd("SplashScreen"); 
		MobclickAgent.onPause(this);
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		isCancel = true;
		MainActivity.this.finish();
	}
	
	/**
	 * 登录
	 */
	private void autoLogin() {
		
		boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
		if (netUsable) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
			StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_USER_LOGIN_URL,
					listener4LoginSuccess,listener4LoginError ){
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {
					String timestamp = SecurityUtil.getTimestamp();
					Map<String, String>  params = new HashMap<String, String>();
					params.put("mobile", mSession.getAccount());
					params.put("password", mSession.getPassword());
					params.put("companyId", Constants.COMPANY_ID);
					params.put(Constants.URL_TIMESTAMP,timestamp );
					params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
					return params;
				}
			};
//	            stringRequest.setTag(TAG);
			stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000, 1, 1.0f));
			mRequestQueue.add(stringRequest);
			mRequestQueue.start();
		}else {
			Toast.makeText(mContext,R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
			startActivity(new Intent(MainActivity.this,LoginActivity.class));
			MainActivity.this.finish();
		}
		return ;
	}
	
	Response.ErrorListener listener4LoginError = new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			Toast.makeText(mContext,error.getMessage(),Toast.LENGTH_SHORT).show();
		}
	};
	
	Response.Listener<String> listener4LoginSuccess = new Response.Listener<String>() {
		@Override
		public void onResponse(String response) {
			String code = JsonUtil.getHeaderCode(response);
			if(Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)){
				JSONObject bodyJsonObject = JsonUtil.getBodyJsonObject(response);
				try {
					
					JSONObject userJsonObject = bodyJsonObject.getJSONObject("customer");//用户信息的key
					String username = userJsonObject.getString("nikeName");
					if(username == null) username="";
					mSession.setUserName(username);
					mSession.setUid(userJsonObject.getString("id"));
					String headImgurl = userJsonObject.getString("headImgurl");
					if(headImgurl == null) headImgurl="";
					mSession.setUserIcon(headImgurl);
					String address = userJsonObject.getString("address");
					if(address == null) address="";
					mSession.setUserAddress(address);
					
				} catch (JSONException e) {
//	                    e.printStackTrace();
					Utils.E("parse login result info json string error!!!",e);
				}
				startActivity(new Intent(mContext,SpecActivity.class));
				MainActivity.this.finish();
			}else {
				Toast.makeText(mContext,JsonUtil.getHeaderErrorInfo(response),Toast.LENGTH_SHORT).show();
				startActivity(new Intent(MainActivity.this,LoginActivity.class));
				MainActivity.this.finish();
			}
		}
	};

}
